# -*- coding: UTF-8 -*-
# 读取数据集，模拟群智感知过程
import random
import match_SP
from seller_SP import SellerAoISP
from buyer_SP import BUDGET, BuyerAoISP
from util import Util

T = 1200
budget = 100
qbuyer = 3
util = Util()


def readNextTime(file):
    t = file.readline().split(' ')[3].strip('\n')
    return int(t)


# 读取文件
cabNames = ["atsfiv", "enyenewl", "objoyhi", "oadwowd", "oowfmu", "etirnfew", "unwrain",
            "iagods", "eydadgio", "icdaheos", "ipdraw", "isnthli", "idjojwa", "aupclik",
            "ucdewy", "abcoij"]
cabFileNames = []
for c in cabNames:
    cabFileNames.append("./fcycabdata/new_"+c+".txt")


def getDatasetSB(T, qseller, qbuyer, avgbudget):
    cabFiles = []
    for fn in cabFileNames:
        f = open(fn, 'r')
        cabFiles.append(f)
    s = []
    for icab in range(min([len(cabFiles), qseller])):
        file = cabFiles[icab]
        updatetimes = []
        tend = readNextTime(file)
        tnow = readNextTime(file)
        tlen = tend-tnow
        while tlen < T:
            updatetimes.insert(0, tend-tnow)
            tnow = readNextTime(file)
            tlen = tend-tnow
        l = len(updatetimes)
        price = [l+random.randint(5, 30) for _ in range(qbuyer)]
        seller = SellerAoISP(icab, qbuyer, T, l, price, updatetimes)
        s.append(seller)
    # 初始化买家
    b = []
    for i in range(qbuyer):
        # 随机生成预算
        buyer = BuyerAoISP(i, T, random.randint(avgbudget-10, avgbudget+10))
        b.append(buyer)
    for file in cabFiles:
        file.close()
    return s, b


if __name__ == "__main__":
    """
    for budget in range(60, 220, 20):
        print(["budget:", budget])
        # 转换数据格式，初始化数据源
        s, b = getDatasetSB(T, 15, 2, budget)
        pdata, bw, baoi = match_SP.match_AoISP(T, s, b)
        util.plotDoubleData_cab(pdata['x'], pdata['sellerProfit'],
                                pdata['buyerAoI'], 'round', 'seller profit', 'buyer AoI cost')
    """
    budget = 200
    qbuyer = 10
    s, b = getDatasetSB(T, 15, qbuyer, budget)
    w_budget = []
    for buyer in b:
        w_budget.append(buyer.budget)
    pdata, w_AoISP, buyeraoi_AoISP = match_SP.match_AoISP(T, s, b)
    w_usedb = util.getUsedBudget(s, b)
    x = range(qbuyer)

    util.plotDoubleBar(x, w_budget, w_usedb, 'buyer id',
                       'budget', 'overall payment')
